package com.kede.api.stand.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.kede.api.stand.service.ResourceService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.time.LocalDateTime;

/**
* @author 11856
* @description 针对表【resource_file】的数据库操作Service实现
* @createDate 2023-04-26 14:42:31
*/
@Service
@Data
public class ResourceServiceImpl  implements ResourceService {

    @Value("${file.qrcode.logo}")
    private String logoPath;

    /**
     * 存放文件的地址
     * @param key
     * @return
     */
    @Value("${file.location}")
    private String location;


    @Override
    public String createShareQrcode(String title,String con) {
        String dirname = DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd");
        String filename = UUID.fastUUID().toString(true);
        StringBuilder filepath = new StringBuilder();
        filepath.append("/").append("shareimg");
        filepath.append("/").append(dirname).append("/").append(filename).append(".jpg");
        try {
            buildImg(title,con,FileUtil.file(location + filepath.toString()));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return filepath.toString();
    }

    public void buildImg(String title,String con,File dest) throws FileNotFoundException {
        File file = new File(location + File.separator + "bg.jpg");
        QrConfig qrConfig = new QrConfig();
        qrConfig.setCharset(CharsetUtil.CHARSET_UTF_8);
        qrConfig.setMargin(0);
        qrConfig.setWidth(134);
        qrConfig.setHeight(134);
        qrConfig.setImg(new File(logoPath));
        //设置logo
        // 设置前景色，既二维码颜色（青色）
        qrConfig.setErrorCorrection(ErrorCorrectionLevel.H);
        BufferedImage generate = QrCodeUtil.generate(con, qrConfig);

        BufferedImage srcimg = ImgUtil.read(file);
        Image image = ImgUtil.pressText(
                srcimg,
                //文字
                title, Color.BLACK,
                new Font("微软雅黑", Font.PLAIN, 22),
                //x坐标修正值。 默认在中间，偏移量相对于中间偏移
                0,
                //y坐标修正值。 默认在中间，偏移量相对于中间偏移
                -40,
                //透明度：alpha 必须是范围 [0.0, 1.0] 之内（包含边界值）的一个浮点数字
                1f
        );
        ImgUtil.pressImage(image,dest,generate,114,98,1f);
    }


}




